package com.sloth.bear.service.impl;

import com.sloth.bear.config.OssProperties;
import com.sloth.bear.service.OssStorageService;
import com.UpYun;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 又拍云存储服务实现
 */
@Slf4j
@Service("upyunStorageService")
@ConditionalOnProperty(name = "oss.type", havingValue = "upyun")
public class UpYunStorageServiceImpl implements OssStorageService {

    private final UpYun upYun;
    private final String domain;

    public UpYunStorageServiceImpl(OssProperties ossProperties) {
        OssProperties.UpYunConfig config = ossProperties.getUpyun();
        this.upYun = new UpYun(config.getBucket(), config.getOperator(), config.getPassword());
        this.domain = config.getDomain();
        log.info("又拍云存储服务初始化成功，bucket: {}", config.getBucket());
    }

    @Override
    public String upload(MultipartFile file, String filePath) throws Exception {
        boolean result = upYun.writeFile(filePath, file.getBytes(), true);
        if (!result) {
            throw new RuntimeException("上传文件到又拍云失败");
        }
        // 确保domain和filePath之间只有一个斜杠
        return domain + "/" + filePath;
    }

    @Override
    public boolean delete(String filePath) {
        try {
            return upYun.deleteFile(filePath);
        } catch (Exception e) {
            log.error("删除文件失败: {}", filePath, e);
            return false;
        }
    }
}
